package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class SessionController {
    @Autowired
    private IUserService userService;

    @PostMapping("/sessions")
    public Object login(String email,String password){
        JSONResult json = new JSONResult();
        try {
            User user = userService.login(email,password);
            //拦截器中使用
            UserContext.setCurrentUser(user);
            //回调函数中的data,给sessionStorage使用
            json.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    @DeleteMapping("/sessions")
    public Object logout(HttpSession session){
        JSONResult json = new JSONResult();
        session.invalidate();
        return json;
    }
}
